package com.cn.zy.protocol.client;

import com.cn.zy.protocol.domain.School;
import com.google.protobuf.InvalidProtocolBufferException;

import java.text.DecimalFormat;

/**
 * @author zhangyi
 * @date 2019/2/25 14:43
 */
public class ClientSchool {
    public static void main(String[] args) throws InvalidProtocolBufferException {
        School.Person.Builder person = School.Person.newBuilder();
        person.setId(1);
        person.setAge(100);
        person.setIsSex(true);
        person.setName("java");

        School.Class.Builder clazz = School.Class.newBuilder();
        clazz.setClassNum(1);
        clazz.setGradeNum(22);
        clazz.addStudents(person);
        person.setName("c#");
        clazz.addStudents(person);
        System.out.println(clazz);

        /**
         * Result:
         *
         * grade_num: 22
         * class_num: 1
         * students {
         *   id: 1
         *   age: 100
         *   name: "java"
         *   is_sex: true
         * }
         * students {
         *   id: 1
         *   age: 100
         *   name: "c#"
         *   is_sex: true
         * }
         *
         */

        /**
         * 解析
         */
        School.Class build = clazz.build();
//        List<School.Person> studentsList = build.getStudentsList();
//        for(School.Person p : studentsList){
//            System.out.println(p.toString());
//        }

//        数组
        StringBuffer stringBuffer = new StringBuffer();
        for(byte b : build.toByteArray()){
            stringBuffer.append(b);
        }
        System.out.println("压缩之后的长度是:"+stringBuffer.length());
        int newLen = stringBuffer.length();
        stringBuffer.delete(0,stringBuffer.length());
        System.out.println("删除之后的长度:"+stringBuffer.length());
        byte[] bytes = build.toByteArray();
        School.Class aClass = School.Class.parseFrom(bytes);
        stringBuffer.append(aClass.toString());
        System.out.println("压缩之前的长度是:"+stringBuffer.length());
        int oldLen = stringBuffer.length();
        System.out.println(aClass.toBuilder());
        System.out.println(newLen+"--"+oldLen);
        double result = (double) (newLen/oldLen);
        String format = new DecimalFormat("0.00").format(result);
        System.out.println("压缩率是:"+format);


    }

}
